package com.adan.checkcode.service.impl;

import com.adan.checkcode.service.SendCodeService;
import com.adan.checkcode.utils.MailUtil;
import com.adan.checkcode.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version: 1.0
 * @Author: adan
 * @description: 发送邮箱/手机验证码
 * @date: 2023-06-24 23:18
 */
@Slf4j
@Service
public class SendCodeServiceImpl implements SendCodeService {

    @Value("${SMS.signName}")
    private String signName;

    @Value("${SMS.templateCode}")
    private String templateCode;

    public final Long CODE_TTL = 120L;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void sendEMail(String param, String code) {
        // 1. 向用户发送验证码
        if (isEmail(param)) {
            // 发送邮箱
            try {
                MailUtil.sendTestMail(param, code);
            } catch (MessagingException e) {
                e.printStackTrace();
                log.error("发送邮箱到:{}失败", param);
                throw new RuntimeException("发送邮箱失败");
            }
        } else if (isPhone(param)) {
            // 发送手机短信
            SMSUtils.sendMessage(signName, templateCode, param, code);
        } else {
            // 字符串既不是邮箱也不是手机
            throw new RuntimeException("格式出错");
        }
        // 2. 将验证码缓存到redis，TTL设置为2分钟
        redisTemplate.opsForValue().set(code, param, CODE_TTL, TimeUnit.SECONDS);
    }


    public static boolean isEmail(String str) {
        Pattern p = Pattern.compile("^\\w+@(\\w+\\.)+[a-z]{2,3}$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static boolean isPhone(String str) {
        Pattern p = Pattern.compile("^1[0-9]{10}$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

}
